from rest_framework import serializers
import re
from datetime import datetime, timedelta

from users.models import UserProfile, VerifyCode
from Diary_django.settings import REGEX_MOBILE


class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('username', 'gender', 'mobile', 'birthday', 'want_to_say')


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        # 手机号是否符合规则
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError('手机号非法')
        # 手机号是否被注册过
        if UserProfile.objects.filter(mobile=mobile):
            raise serializers.ValidationError('手机号已注册')
        # 设置验证码发送频率
        time_interval = datetime.now() - timedelta(minutes=5)
        if VerifyCode.objects.filter(send_time__gt=time_interval, mobile=mobile):
            raise serializers.ValidationError('验证发送频率过快，请稍后')

        return mobile


class UserRegSerializer(serializers.ModelSerializer):
    code = serializers.CharField(write_only=True, max_length=6, min_length=6)
    mobile = serializers.CharField(max_length=11)
    password = serializers.CharField(write_only=True)

    def validate_mobile(self, mobile):
        user = UserProfile.objects.filter(mobile=mobile)
        if user:
            raise serializers.ValidationError('用户已注册')
        return mobile

    def validate_code(self, code):
        verify_code = VerifyCode.objects.filter(mobile=self.initial_data['mobile'], code=code).order_by('-send_time')[0]
        if verify_code:
            time_interval = datetime.now() - timedelta(minutes=5)
            if time_interval > verify_code.send_time:
                raise serializers.ValidationError('验证码过期')

        else:
            raise serializers.ValidationError('验证码错误')
        return code

    def validate(self, attrs):
        attrs['username'] = attrs['mobile']
        del attrs["code"]
        return attrs

    class Meta:
        model = UserProfile
        fields = ('code', 'mobile', 'password')








